package sanphone.com.runningschool.Saying;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import sanphone.com.runningschool.BaseActivity;
import sanphone.com.runningschool.ForceOffline;
import sanphone.com.runningschool.InterfaceLocation;
import sanphone.com.runningschool.R;
import sanphone.com.runningschool.RequestHttp.RequestHttp;
import sanphone.com.runningschool.entity.Comment;

public class SayingDetailActivity extends BaseActivity implements View.OnClickListener {

    private TextView publisher_name;
    private TextView saying_content;
    private ListView commentListView;
    private String questionId, content, userName, userId,title,nickName;
    private List<Comment> commentList;
    private ImageView hide;
    private EditText comment_text;
    private Button send;
    private TextView saying_title;
    private ImageView delete;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_saying_detail);
        SharedPreferences sprf = getSharedPreferences("data", MODE_PRIVATE);
        ForceOffline offline = new ForceOffline(sprf.getString("schoolId", null), this);
        offline.check();
        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        initView();
         getData();
        getDataFromInternet();
        setData();
        hide.setOnClickListener(this);
        comment_text.setOnClickListener(this);
        send.setOnClickListener(this);
    }

    private void initView() {
        publisher_name = findViewById(R.id.publisher_name);
        saying_content = findViewById(R.id.saying_content);
        commentListView = findViewById(R.id.comment_list);
        hide = findViewById(R.id.hide);
        comment_text = findViewById(R.id.comment_text);
        send = findViewById(R.id.send);
        saying_title = findViewById(R.id.saying_title);
        delete=findViewById(R.id.s_delete);

    }

    public void getData(){
        SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE);
        userId = pref.getString("schoolId", null);
        nickName=pref.getString("nickName",null);
        Intent intent = getIntent();
        userName = intent.getStringExtra("userName");
        content = intent.getStringExtra("context");
        questionId = intent.getStringExtra("questionId");
        title=intent.getStringExtra("questionTitle");
    }
    public void setData(){
        saying_title.setText(title);
        publisher_name.setText(userName);
        saying_content.setText(content);
        if(nickName.equals(userName)){
            delete.setVisibility(View.VISIBLE);
            delete.setOnClickListener(this);
        }
        else{
            delete.setVisibility(View.GONE);
        }
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                SayingDetailActivity.this.finish();
                break;
            default:
                break;
        }
        return true;
    }


    private void getDataFromInternet() {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                RequestHttp requestHttp = new RequestHttp(InterfaceLocation.getLocation() + "showResponse?questionId=" + questionId,SayingDetailActivity.this);
                try {
                    String response = requestHttp.get();
                    String data = new JSONObject(response).getString("data");
                    Gson gson = new Gson();
                    commentList = gson.fromJson(data, new TypeToken<List<Comment>>() {
                    }.getType());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            commentListView.setAdapter(new CommentListViewAdapter(SayingDetailActivity.this, commentList));
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.send:
                InputMethodManager imm3 = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm3.hideSoftInputFromWindow(comment_text.getWindowToken(), 0);
                sendComment();
                break;
            case R.id.hide:
                InputMethodManager imm2 = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm2.hideSoftInputFromWindow(comment_text.getWindowToken(), 0);
                break;
            case R.id.s_delete:
                AlertDialog.Builder builder=new AlertDialog.Builder(SayingDetailActivity.this);
                builder.setTitle("温馨提示");
                builder.setMessage("是否删除信息？");
                builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        deleteQuestion();
                    }
                });
                builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                builder.show();
                break;
        }

    }

    private void sendComment() {
        final String content = comment_text.getText().toString();
        final String sendString;
        try {
            sendString = URLEncoder.encode(content,"UTF-8");
        Log.e("sendComment", userId + content + questionId);
        if (content.equals("")) {
            Toast.makeText(SayingDetailActivity.this, "内容不能为空！", Toast.LENGTH_SHORT).show();
        } else {
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    JSONObject json = new JSONObject();
                    try {
                        json.put("questionId", questionId);
                        json.put("userId", userId);
                        json.put("answerText", sendString);
                        RequestHttp requestHttp = new RequestHttp(InterfaceLocation.getLocation() + "responseQuestion",SayingDetailActivity.this);
                        String response = requestHttp.post(json);
                        JSONObject responseJson = new JSONObject(response);
                        Log.e("sendComment", responseJson.getString("data"));
                        if (responseJson.getString("data").equals("评论成功")) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    comment_text.setText("");
                                    Toast.makeText(SayingDetailActivity.this, "评论成功！", Toast.LENGTH_SHORT).show();
                                }
                            });
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(SayingDetailActivity.this, "问题不存在，无法回复！", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                        getDataFromInternet();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
            executorService.shutdown();
        }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }

    public void deleteQuestion(){
        ExecutorService executorService=Executors.newSingleThreadExecutor();
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject json=new JSONObject();
                    json.put("schoolId",userId);
                    json.put("questionId",questionId);
                    RequestHttp requestHttp=new RequestHttp(InterfaceLocation.getLocation()+"userDeleteQuestion",SayingDetailActivity.this);
                    String respone=requestHttp.post(json);
                    JSONObject responeJson=new JSONObject(respone);
                    String data=responeJson.getString("data");
                    if(data.equals("删除成功")){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(SayingDetailActivity.this,"问题删除成功！",Toast.LENGTH_SHORT).show();
                                SayingDetailActivity.this.finish();
                            }
                        });

                    }else{
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(SayingDetailActivity.this,"问题删除失败,请重试！",Toast.LENGTH_SHORT).show();
                            }
                        });

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });
        executorService.shutdown();
    }


}
